from typing import Any, List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api import deps
from app.models.user import User
from app.schemas.report import (
    ReportCreate, ReportUpdate, ReportResponse,
    ReportInstanceCreate, ReportInstanceResponse
)
from app.services import report as report_service


router = APIRouter()


@router.get("/", response_model=List[ReportResponse])
async def read_reports(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    report_type: Optional[str] = None,
    project_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取报表模板列表，可按类型和项目筛选"""
    reports = await report_service.get_reports(
        db=db, skip=skip, limit=limit,
        report_type=report_type, project_id=project_id
    )
    return reports


@router.post("/", response_model=ReportResponse, status_code=status.HTTP_201_CREATED)
async def create_report(
    *,
    db: AsyncSession = Depends(deps.get_db),
    report_in: ReportCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建报表模板"""
    # 检查权限：只有超级用户或项目管理员可以创建报表模板
    if not current_user.is_superuser and not current_user.is_project_manager:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    report = await report_service.create_report(
        db=db, obj_in=report_in, creator_id=current_user.id
    )
    return report


@router.get("/{report_id}", response_model=ReportResponse)
async def read_report(
    *,
    db: AsyncSession = Depends(deps.get_db),
    report_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定报表模板详情"""
    report = await report_service.get_report_by_id(db=db, id=report_id)
    if not report:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report not found",
        )
    return report


@router.put("/{report_id}", response_model=ReportResponse)
async def update_report(
    *,
    db: AsyncSession = Depends(deps.get_db),
    report_id: int,
    report_in: ReportUpdate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """更新报表模板"""
    report = await report_service.get_report_by_id(db=db, id=report_id)
    if not report:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report not found",
        )
    # 检查权限：只有报表创建者、超级用户或项目管理员可以更新报表模板
    if (report.creator_id != current_user.id 
            and not current_user.is_superuser 
            and not current_user.is_project_manager):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    report = await report_service.update_report(db=db, db_obj=report, obj_in=report_in)
    return report


@router.delete("/{report_id}", response_model=ReportResponse)
async def delete_report(
    *,
    db: AsyncSession = Depends(deps.get_db),
    report_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除报表模板"""
    report = await report_service.get_report_by_id(db=db, id=report_id)
    if not report:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report not found",
        )
    # 检查权限：只有报表创建者、超级用户或项目管理员可以删除报表模板
    if (report.creator_id != current_user.id 
            and not current_user.is_superuser 
            and not current_user.is_project_manager):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    report = await report_service.delete_report(db=db, id=report_id)
    return report


# 报表实例相关路由
@router.get("/instances/", response_model=List[ReportInstanceResponse])
async def read_report_instances(
    db: AsyncSession = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    report_id: Optional[int] = None,
    project_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取报表实例列表，可按报表模板和项目筛选"""
    instances = await report_service.get_report_instances(
        db=db, skip=skip, limit=limit,
        report_id=report_id, project_id=project_id
    )
    return instances


@router.post("/instances/", response_model=ReportInstanceResponse, status_code=status.HTTP_201_CREATED)
async def create_report_instance(
    *,
    db: AsyncSession = Depends(deps.get_db),
    instance_in: ReportInstanceCreate,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """创建报表实例（生成报表）"""
    # 检查报表模板是否存在
    report = await report_service.get_report_by_id(db=db, id=instance_in.report_id)
    if not report:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report template not found",
        )
    
    # 创建报表实例
    instance = await report_service.create_report_instance(
        db=db, obj_in=instance_in, creator_id=current_user.id
    )
    return instance


@router.get("/instances/{instance_id}", response_model=ReportInstanceResponse)
async def read_report_instance(
    *,
    db: AsyncSession = Depends(deps.get_db),
    instance_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """获取特定报表实例详情"""
    instance = await report_service.get_report_instance_by_id(db=db, id=instance_id)
    if not instance:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report instance not found",
        )
    return instance


@router.delete("/instances/{instance_id}", response_model=ReportInstanceResponse)
async def delete_report_instance(
    *,
    db: AsyncSession = Depends(deps.get_db),
    instance_id: int,
    current_user: User = Depends(deps.get_current_active_user),
) -> Any:
    """删除报表实例"""
    instance = await report_service.get_report_instance_by_id(db=db, id=instance_id)
    if not instance:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Report instance not found",
        )
    # 检查权限：只有报表实例创建者、超级用户或项目管理员可以删除报表实例
    if (instance.creator_id != current_user.id 
            and not current_user.is_superuser 
            and not current_user.is_project_manager):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Not enough permissions",
        )
    instance = await report_service.delete_report_instance(db=db, id=instance_id)
    return instance